package com.zy.mc_module.utils;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created on 19/3/2
 * 文本正则校验
 * 数据判断空
 */
public class StringsUtils {

    //----------------------  正则  ----------------------

    /***
     * 判断手机号的正则表达式
     */
    public static boolean isMobile(String tel) {
        if (tel.isEmpty()) {
            ToastUtil.showShort("手机号不能为空");
            return false;
        } else {
            String regExp = "^[1]([3-9])[0-9]{9}$";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(tel);
            if (!m.find()) {
                ToastUtil.showShort("请输入正确的手机号");
                return false;
            } else {
                return true;
            }
        }
    }
    /***
     * 判断手机号的正则表达式
     */
    public static boolean isPhoneNum(String tel) {
        if (tel.isEmpty()) {
            return false;
        } else {
            String regExp = "^[1]([3-9])[0-9]{9}$";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(tel);
            if (!m.find()) {
                return false;
            } else {
                return true;
            }
        }
    }

    /***
     * 显示的昵称如果是手机号就打上星号
     */
    public static String getName(String name) {
        String regExp = "^(1[0-9])\\d{9}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(name);
        if (!m.find()) {
            //不是手机号
            return name;
        } else {
            //是手机号
            return hideTel(name);
        }
    }

    /***
     * 名字正则表达式
     * 2~5个中文
     */
    public static boolean isName(String name) {
        String regExp = "^[\\u4e00-\\u9fa5]{0,}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(name);
        if (!m.find()) {
            //不是姓名
            return false;
        } else {
            //是姓名
            return name.length() >= 2 && name.length() <= 5;
        }
    }

    /***
     * 判断身份证/护照/港澳通行证
     * type:1身份证/2护照/3港澳通行证
     */
    public static boolean isIdNum(String num, int type) {
        boolean isCorrect = false;
        if (type == 1) {
            isCorrect = isIdCard(num);
        } else if (type == 2) {
            String regExp = "^[a-zA-Z0-9]{5,17}$";
            Pattern p = Pattern.compile(regExp);
            isCorrect = p.matcher(num).find();
        } else if (type == 3) {
            String regExp = "^[a-zA-Z0-9]{6,10}$";
            Pattern p = Pattern.compile(regExp);
            isCorrect = p.matcher(num).find();
        }
        return isCorrect;
    }

    /**
     * 18位身份证校验,比较严格校验
     */
    public static boolean isIdCard(String idCard) {
        Pattern pattern1 = Pattern.compile("^(\\d{6})(19|20)(\\d{2})(1[0-2]|0[1-9])(0[1-9]|[1-2][0-9]|3[0-1])(\\d{3})" +
                "(\\d|X|x)?$");
        Matcher matcher = pattern1.matcher(idCard);
        int[] prefix = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        int[] suffix = new int[]{1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2};
        if (matcher.matches()) {
            int idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
            for (int i = 0; i < 17; i++) {
                idCardWiSum += Integer.valueOf(idCard.substring(i, i + 1)) * prefix[i];
            }
            int idCardMod = idCardWiSum % 11;//计算出校验码所在数组的位置
            String idCardLast = idCard.substring(17);//得到最后一位身份证号码

            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if (idCardMod == 2) {
                if (idCardLast.equalsIgnoreCase("x")) {
                    return true;
                } else {
                    return false;
                }
            } else {
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if (idCardLast.equals(suffix[idCardMod] + "")) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 检查邮箱是否合法
     * 限制30位以下
     */
    public static boolean isEmail(String email) {
        if (email.matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) {
            return email.length() <= 30;
        } else {
            return false;
        }
    }

    /***
     * 隐藏姓名-骚操作
     */
    public static String hideName(String name) {
        if (name.length() == 2) {
            StringBuilder stringBuilder = new StringBuilder(name).replace(1, 2, "*");
            return stringBuilder.toString();
        } else if (name.length() > 2) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < name.length() - 2; i++) {
                sb.append("*");
            }
            StringBuilder stringBuilder = new StringBuilder(name).replace(1, name.length() - 1, sb.toString());
            return stringBuilder.toString();
        } else {
            return name;
        }
    }

    /***
     * 隐藏手机号中间4位正则
     */
    public static String hideTel(String tel) {
        try {
            return tel.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        } catch (Exception e) {
            e.printStackTrace();
            return tel;
        }
    }

    /***
     * 隐藏身份证中间8位
     */
    public static String hideIdCard(String idcard) {
        if (idcard.length() >= 18) {
            StringBuilder stringBuilder = new StringBuilder(idcard);
            stringBuilder.replace(6, 14, "********");
            return stringBuilder.toString();
        } else {
            return "";
        }
    }

    /***
     * 校验密码长度6~20位字母和数字组合的密码
     */
    public static boolean checkPwd(String pass) {
        String passRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
        return !TextUtils.isEmpty(pass) && pass.matches(passRegex);
    }

    /***
     * 去掉Html标签
     */
    public static String delHtml(CharSequence charSequence) {
        if (!TextUtils.isEmpty(charSequence)) {
            Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(charSequence);
            return m_html.replaceAll("");
        } else {
            return "";
        }
    }
//    /***
//     * 校验用户名支持中文、大小写字母、数字及“_”
//     */
//    public static boolean checkUserName(String userName) {
//        if (!TextUtils.isEmpty(userName)) {
////            String numRegex = "[0-9]";
////            String chineseRegex = "[\\u4e00-\\u9fa5]";
////            String englishRegex = "[a-zA-Z]";
//            String regex = "^[\\u4e00-\\u9fa5_a-zA-Z0-9_]{0,}$";
//            if (userName.length() >= 5 && userName.length() <= 25) {
//                if (isNumber(userName)) {
//                    return false;
//                }
//                if (userName.matches(regex)) {
//                    return true;
//                }
//            }
//            return false;
//        }
//        return false;
//    }

    /***
     * 校验用户名支持大小写字母、数字及“_”
     */
    public static boolean checkUserName(String userName) {
        if (!TextUtils.isEmpty(userName)) {
//            String numRegex = "[0-9]";
//            String chineseRegex = "[\\u4e00-\\u9fa5]";
//            String englishRegex = "[a-zA-Z]";
            String regex = "^[a-zA-Z0-9_]{0,}$";
            if (userName.length() >= 5 && userName.length() <= 25) {
                if (isNumber(userName)) {
                    return false;
                }
                if (userName.matches(regex)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    /**
     * 判断一个字符串是否是数字。
     *
     * @param string
     * @return
     */
    public static boolean isNumber(String string) {
        if (string == null)
            return false;
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(string).matches();
    }

    /**
     * 判断字符串是否为URL
     * @param urls 用户头像key
     * @return true:是URL、false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式

        Pattern pat = Pattern.compile(regex.trim());//比对
        Matcher mat = pat.matcher(urls.trim());
        isurl = mat.matches();//判断是否匹配
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }
    //----------------------  正则  ----------------------

    //
    //
    //
    //
    //
    //

    /***
     * 数据判空
     * 判断集合是否为null
     * @param t
     * @param <T>
     * @return true空/false非空
     */
    public static <T> boolean isEmpty(T t) {
        if (null != t) {
            if (t instanceof List) {
                return null == t || ((List) t).isEmpty();
            } else if (t instanceof ArrayList) {
                return null == t || ((ArrayList) t).isEmpty();
            } else if (t instanceof Map) {
                return null == t || ((Map) t).isEmpty();
            } else if (t instanceof HashMap) {
                return null == t || ((HashMap) t).isEmpty();
            } else if (t instanceof EditText) {
                String con = ((EditText) t).getText().toString().trim();
                return TextUtils.isEmpty(con);
            } else if (t instanceof TextView) {
                String con = ((TextView) t).getText().toString().trim();
                return TextUtils.isEmpty(con);
            } else if (t instanceof String) {
                String con = (String) t;
                return TextUtils.isEmpty(con);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /***
     * 获取控件文字内容
     */
    public static String getText(View view) {
        if (view instanceof TextView) {
            return ((TextView) view).getText().toString().trim();
        } else if (view instanceof EditText) {
            return ((EditText) view).getText().toString().trim();
        } else {
            return "";
        }
    }

    /***
     * 取数组最小值
     * String[] {"5","2","7","5"}
     */
    public static Map<Integer, String> getMinValue(String[] strs) {
        Map<Integer, String> map = new HashMap<>();
        try {
            if (null != strs && strs.length > 0) {
                for (int i = 0; i < strs.length; i++) {
                    map.put(i, strs[i]);
                }
                for (int i = 0; i < strs.length; i++) {
                    for (int j = 0; j < strs.length - i - 1; j++) {
                        if (Double.parseDouble(strs[j]) > Double.parseDouble(strs[j + 1])) {
                            double temp = Double.parseDouble(strs[j]);
                            strs[j] = strs[j + 1];
                            strs[j + 1] = String.valueOf(temp);
                        }
                    }
                }
            }
            for (Entry<Integer, String> str : map.entrySet()) {
                if (str.getValue().equals(strs[0])) {
                    map.clear();
                    map.put(str.getKey(), strs[0]);
                    break;
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
    }

    /***
     * List<String> 转String
     */
    public static String listToString(List<String> lists) {
        if (!StringsUtils.isEmpty(lists)) {
            return GsonUtil.gsonString(lists).replace("\"", "").replace("[", "").replace("]", "");
        } else {
            return "";
        }
    }

    /***
     * String,String,String 转 List<String>
     */
    public static List<String> stringToList(String str) {
        List<String> list = new ArrayList<>();
        if (!TextUtils.isEmpty(str)) {
            try {
                String[] strs = str.split(",");
                Collections.addAll(list, strs);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static String getCode(String body) {
        Pattern pattern1 = Pattern.compile("(\\d{6})");//提取六位数字
        Matcher matcher1 = pattern1.matcher(body);//进行匹配
        if (matcher1.find()) {//匹配成功
            String code = matcher1.group(0);
            return code;
        } else {
            return "";
        }
    }

    /***
     * 隐藏身中间n位
     */
    public static String hideString(String string, int start, int end) {
        if (!StringsUtils.isEmpty(string) && string.length() >= start + end) {
            StringBuilder stringBuilder = new StringBuilder();
            String startStr = string.substring(0, start);
            String endStr = string.substring(string.length() - end);
            stringBuilder.append(startStr);
            stringBuilder.append("****");
            stringBuilder.append(endStr);
            return stringBuilder.toString();
        } else {
            return "";
        }
    }
}
